package gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;

import engine.Logger;
import engine.Logger.LogListener;

public class StartWindow extends JFrame implements LogListener{
	
	public static final boolean DEBUG = false;
	
	JPanel panel;
	CompareButton compare;
	JButton load;
	JButton threshold;
	private static JTextArea log;
	
	private static int WINDOW_W;
	private static int WINDOW_H;
	private final Color light = Color.WHITE;
//	private final Color light = new Color( (int)(100 +Math.random()*150),(int)(100 +Math.random()*150), (int)(100 +Math.random()*150));
	private final Color dark = new Color(100,100,200);
	
	private static final int IPADY_DIFF = 50;
	
	static {
		if (DEBUG) {
			WINDOW_W = 700;
			WINDOW_H = 400;
		} else {
			WINDOW_H = 120;
			WINDOW_W = 500;
		}
	}
	
	public StartWindow(){
		panel= new JPanel();
		compare = new CompareButton(this);
		load = new LoadButton(compare);
		threshold = new ThresholdButton();
		styleComponents(panel, compare, load, threshold);
		
		compare.setIcon(new ImageIcon("Compare.png"));
		threshold.setIcon(new ImageIcon("Thres.png"));
		load.setIcon(new ImageIcon("Load.png"));
		
		
		
		
		setTitle("AESP");
	
		add(panel);
		panel.setLayout(new BorderLayout());
		
		JPanel buttonPanel = new JPanel();
		buttonPanel.setLayout(new GridBagLayout());
		
		GridBagConstraints c = new GridBagConstraints();
		
		c.fill = GridBagConstraints.BOTH;
		c.weightx = 0.5f;
		
		c.gridx = 0;
		c.gridy = 0;
		if (!DEBUG)
			c.ipady = WINDOW_H - IPADY_DIFF;
		
		buttonPanel.add(compare, c);
		
		c.gridx = 1;
		buttonPanel.add(load, c);
		
		c.gridx = 2;
		buttonPanel.add(threshold, c);
		
		panel.add(buttonPanel, BorderLayout.NORTH);
		
		if (DEBUG) {
			
			log =  new JTextArea();
			log.setPreferredSize(new Dimension(WINDOW_W,WINDOW_H-IPADY_DIFF));
			log.setEditable(false);
			
			panel.add(log, BorderLayout.CENTER);
			Logger.addLogListener(this);
		} else {
//			buttonPanel.setPreferredSize(new Dimension(WINDOW_W, WINDOW_H));
		}

		Dimension size = new Dimension(WINDOW_W, WINDOW_H+5);
		setPreferredSize(size);
//		setMinimumSize(size);
//		setMaximumSize(size);
		if (!DEBUG)
			setResizable(false);
		
		setVisible(true);
		
		pack();
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		
	}

	private void styleComponents(Component ... c) {
		for(Component com : c){
			com.setBackground(light);
			com.setForeground(dark);
		}
		
	}

	@Override
	public void handleMessage(String msg) {
		
		String[] msgs = log.getText().split("\n");
		
		StringBuilder sb = new StringBuilder();
		
		sb.append(msg+"\n");
		
		for (int i=0; i<msgs.length && i<50; i++) {
			sb.append(msgs[i]+"\n");
		}
		log.setText(sb.toString());
		
	}

}
